package com.century.sjt.fragment;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.adapter.InviteAdapter;
import com.century.sjt.entity.Invite;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:周玲波
 * @Description: 已邀请人员
 * @date : 2016/8/16 10:11
 */
public class InPeopleFragment extends Fragment{
    private TextView tvAmount;
    private String totalAmount;

    private ListView listView;
    private final Invite aInvite = new Invite();
    private InviteAdapter adapter;
    private SwipeRefreshLayout mSwipeLayout;
    private RequestQueue mQueue;
    private List<Invite> mDatalist= new ArrayList<>();
    private Handler mHandler;
    private String pageSize="10";
    private int iCurrPage=1;
    private Boolean isDataChangeOk=true;
    private TextView icon_money;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sjt_inpeople_fragment, null);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mQueue = Volley.newRequestQueue(getActivity());

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk=true;
                        mDatalist.clear();
                        iCurrPage = 1;
                        GetinviteDetail();
                        break;
                    case 3:
                        if(isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            iCurrPage++;
                            GetinviteDetail();
                        }
                        break;

                }
            }
        };

        adapter = new InviteAdapter(getActivity(), mDatalist,mQueue);

        initViews();

        GetinviteDetail();
//        QueryInviteAmount();


    }

    private void initViews() {
        tvAmount=(TextView)getView().findViewById(R.id.tv_invite_mamy);
        icon_money = (TextView) getView().findViewById(R.id.icon_money);
        listView = (ListView)getView().findViewById(R.id.list_pt_record);
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout)getView(). findViewById(R.id.activity_list_refesh);
        listView.setAdapter(adapter);
        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        icon_money.setTypeface(iconfont);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 获取邀请详情
     */
    private void GetinviteDetail() {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.inviteDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    TipUtil.log("获取邀请列表", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("200")) {//成功
                        if (data.has("amount")) {
                            isDataChangeOk = false;
                            JSONArray inviteCountList=data.getJSONArray("inviteCountList");
                            if (iCurrPage == 1 && inviteCountList.length() == 0) {
//                                TipUtil.showToast("暂无交易记录", mContext);
                            } else {
//                                TipUtil.showToast("无更多数据",PayTransactionActivity.this);
                            }
                        }
                        String amount = data.getString("amount");
                        tvAmount.setText(amount+"元");
                        JSONArray inviteCountList=data.getJSONArray("inviteCountList");
                        for (int i = 0; i < inviteCountList.length(); i++) {
                            JSONObject item = (JSONObject) inviteCountList.get(i);
//
                            Invite mInvite = new Invite();
                            mInvite.setInviteeId(item.getString("inviteeId"));
                            mInvite.setName(item.getString("name"));
                            mInvite.setMobile(item.getString("mobile"));
                            mInvite.setInvitedAmount(item.getString("invitedAmount"));
                            mInvite.setRegTime(item.getString("regTime"));
                            mInvite.setImage(item.getString("image"));

                            mDatalist.add(i,mInvite);
                        }
                        Message msg = new Message();
                        msg.what = 1;
                        mHandler.sendMessage(msg);


                    } else {//失败
                        TipUtil.showToast(message,getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("paging.pageSize",Constant.PAGESIZE+"");
                map.put("paging.currentPage",String.valueOf(iCurrPage));
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }

    /**
     * 获取邀请详情
     */
    private void QueryInviteAmount() {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.QueryInviteAmount, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    TipUtil.log("获取邀请总额", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
//                    JSONObject aData=res.getJSONObject("data");
                    Log.e("data",res.toString());
                    if (code.equals("200")) {//成功
//                        mDatalist.clear();
                        String aData=res.getString("data");
                        tvAmount.setText(aData.toString()+"元");




                    } else {//失败
                        TipUtil.showToast(message,getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }


}
